package com.jeeplus.common.utils.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jeeplus.common.config.Global;
import com.jeeplus.modules.web.model.WxLoginModel;
import com.jeeplus.modules.web.model.WxLoginTypeEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liangbing
 * @version 1.0
 * @date 2021/4/19 18:51
 * @description xxx
 */
public class JwtTokenUtil {
    /**
     * token秘钥，请勿泄露，请勿随便修改
     */
    public static final String SECRET = "038687ac299d4f3a8944dac4bd83d0d7";

    /**
     * token 过期时间: 30天
     */
    public static final int calendarField = Calendar.DATE;
    public static final String tokenExpiryDays = Global.getConfig("tokenExpiryDays");
    public static final int calendarInterval = Integer.parseInt(tokenExpiryDays);

    /**
     * JWT生成Token.<br/>
     * <p>
     * JWT构成: header, payload, signature
     *
     * @param loginModel 登录成功后用户user_id, 参数user_id不可传空
     */
    public static String createToken(WxLoginModel loginModel) throws Exception {
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        // header Map
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // header
                .withClaim("iss", "Service") // payload
                .withClaim("aud", "APP")
                .withClaim("phoneNumber", loginModel.getPhoneNumber())
                .withClaim("type", loginModel.getType().ordinal())
                .withClaim("hallIds", loginModel.getHallIds())
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time
                .sign(Algorithm.HMAC256(SECRET)); // signature

        return token;
    }

    /**
     * 解密Token
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            // e.printStackTrace();
            // token 校验失败, 抛出Token验证非法异常
            e.printStackTrace();
            return null;
        }
        return jwt.getClaims();
    }

    /**
     * 根据Token获取phone number
     * @param token
     * @return phoneNumber
     */
    public static WxLoginModel getAppLoginModel(String token) {
        WxLoginModel loginModel = new WxLoginModel();
        token = token.replaceAll("Bearer ", "");
        Map<String, Claim> claims = verifyToken(token);

        if (claims == null) {
            return null;
        }

        // 过期
        Claim expClaim = claims.get("exp");
        if (null == expClaim || expClaim.asLong() == 0L) {
            return null;
        }

        // 过期时长，单位是秒
        Long exp = expClaim.asLong();
        if (System.currentTimeMillis() - exp * 1000L > 0L) {
            return null;
        }

        // 手机号
        Claim phoneNumberClaim = claims.get("phoneNumber");
        if (null == phoneNumberClaim || StringUtils.isEmpty(phoneNumberClaim.asString())) {
            return null;
        }
        loginModel.setPhoneNumber(phoneNumberClaim.asString());

        // 类型
        Claim typeClaim = claims.get("type");
        if (null == typeClaim) {
            return null;
        }
        loginModel.setType(WxLoginTypeEnum.values()[typeClaim.asInt()]);

        // 棋牌室ids
        Claim hallIdsClaim = claims.get("hallIds");
        if (null != hallIdsClaim) {
            loginModel.setHallIds(hallIdsClaim.asString());
        }

        return loginModel;
    }
}
